//
//  AddToPlayListStep2ViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/12.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD

private let headerIdentifier = "AddToPlayListSectionHeader"
private let playListTableCellIdentifier = "PlayListTableCell"

class AddToPlayListStep2ViewController: BaseViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var tableView: UITableView!
  
  
  // MARK: - Private vars
  
  private var playlists = Playlist.getAll()
  private var playlistNameTextField = UITextField()
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: playListTableCellIdentifier, bundle: nil), forCellReuseIdentifier: playListTableCellIdentifier)
    tableView.register(UINib(nibName: headerIdentifier, bundle: nil), forHeaderFooterViewReuseIdentifier: headerIdentifier)
    
    tableView.contentInset = UIEdgeInsets.init(top: 20, left: 0, bottom: 10, right: 0)
    tableView.scrollIndicatorInsets = tableView.contentInset
  }
  
  private func getSelectedAudioIDs() -> String {
    let selectedAudioIDs = selectedAudios.map { "\($0.id)" }.joined(separator: ",")
    return selectedAudioIDs
  }
  
  // MARK: - Public vars
  
  var selectedAudios = [Audio]()
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prepareUI()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func createPlaylist() {
    let alert = UIAlertController(title: "创建听单", message: "请输入听单名称", preferredStyle: .alert)
    let cancelAction = UIAlertAction (
      title: "取消",
      style: .cancel) { _ in
        
    }
    let createAction = UIAlertAction (
      title: "创建",
      style: .default) { _ in
        if let playlistNameTextField = alert.textFields?.first,
          let playlistName = playlistNameTextField.text,
          playlistName.trim().count > 0 {
          
          try! Playlist.createPlaylist (
            name: playlistName,
            audioIDs: ""
          )
          
          self.playlists = Playlist.getAll()
          self.tableView.reloadData()
        }
    }
    
    alert.addAction(cancelAction)
    alert.addAction(createAction)
    
    alert.addTextField { textField in
      textField.placeholder = "听单名称"
    }
    
    present(alert, animated: true)
  }
  
  // MARK: - Public methods
  
}

extension AddToPlayListStep2ViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return playlists != nil ? playlists!.count : 0
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: playListTableCellIdentifier, for: indexPath) as! PlayListTableCell
    cell.prepare(playlist: playlists![indexPath.row])
    return cell
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier) as! AddToPlayListSectionHeader
    let backgroundView = UIView(frame: header.bounds)
    backgroundView.backgroundColor = .clear
    header.backgroundView = backgroundView
    header.headerLabel.text = "请选择需要加入的听单"
    return header
  }
}

extension AddToPlayListStep2ViewController: UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let playlist = playlists![indexPath.row]
    do {
      try playlist.appendUnique(audioIDs: getSelectedAudioIDs())
      HUD.flash(.labeledSuccess(title: "加入听单成功", subtitle: nil), delay: 1.5)
      let nav = navigationController as! BaseNavigationController
      nav.dismissDelegate?.dismiss(navigationController: nav, completion: nil)
      NotificationCenter.default.post(name: .audioDidAddedToPlaylist, object: nil)
    } catch {
      HUD.flash(.labeledError(title: "加入听单失败", subtitle: "请重试"), delay: 1.5)
    }
    
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 70
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return AddToPlayListSectionHeader.defaultHeight
  }
}
